<template>
  <el-upload
    :action="uploadUrl"
    :data="ossData"
    :show-file-list="showFileList"
    :before-upload="handleBeforeUpload"
    :on-success="handleUploadSuccess"
    :on-error="handleUploadError"
    :multiple="multiple"
    :accept="accept"
    :limit="limit"
    :drag="drag"
    :on-progress="handleProgress"    
    class="w-full"
  >
    <slot></slot>
    <el-progress v-if="progress && (percent > 0 && percent < 100)" :percentage="percent" class="my-2"/>
  </el-upload>
</template>

<script>
import api from '@/common/api'
import myMessage from '@/common/message'

export default {
  name: 'AliyunOssUpload',
  props: {
    // 限制文件类型，例如：image/*，video/*，audio/*
    accept: {
      type: String,
      default: ''
    },
    // 是否显示已上传文件列表
    showFileList: {
      type: Boolean,
      default: true
    },
    // 是否支持多文件上传
    multiple: {
      type: Boolean,
      default: false
    },
    // 最大上传数量
    limit: {
      type: Number,
      default: 1
    },    
    // 是否开启拖拽上传
    drag: {
      type: Boolean,
      default: false
    },
    // 是否显示进度条
    progress: {
      type: Boolean,
      default: true
    },
    type: {
      type: String,
      default: 'unknown'
    }
  },
  data() {
    return {
      uploadUrl: '',    // OSS上传地址
      ossData: {},      // OSS表单数据
      percent: 0        // 当前进度
    }
  },
  methods: {
    // 上传前获取OSS配置
    async handleBeforeUpload(file) {
      try {
        const {name, type} = file;
        const res = await api.admin_getOssUploadPolicy(name, type)
        const { host, policy, signature, accessId, key } = res.data.data
        
        this.uploadUrl = host
        this.ossData = {
          key,
          policy,
          OSSAccessKeyId: accessId,
          signature,
          success_action_status: '200'
        }
        return true
      } catch (error) {
        this.$message.error('获取上传配置失败')
        return false
      }
    },

    // 上传成功回调
    handleUploadSuccess(res, file) {
      const url = this.uploadUrl + '/' + this.ossData.key

      const data = {
        url,
        size: file.size,
        type: this.type,
        name: file.name // 原始文件名
      }

      api.admin_ossFileUploadNotify(data).then(res => {
        this.$emit('success', {
          url,
          file:file.raw,
          name: file.name // 原始文件名
        })
        this.$message.success('上传成功');
      })
    },

    // 上传失败回调
    handleUploadError() {
      this.$message.error('上传失败')
    },

    // 上传进度回调
    handleProgress(event, file, fileList) {
      this.percent = Math.floor(event.percent)
    }
  }
}
</script> 
<style scoped>

</style>
